package com.ltcode.auth.infrastructure.service;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.ltcode.auth.application.service.CaptchaGeneratorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Base64;

/**
 * 验证码生成器服务实现
 * 
 * @author ltcode
 * @since 2024-01-01
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CaptchaGeneratorServiceImpl implements CaptchaGeneratorService {

    @Resource(name = "charCaptchaProducer")
    private DefaultKaptcha charCaptchaProducer;

    @Resource(name = "mathCaptchaProducer")
    private DefaultKaptcha mathCaptchaProducer;

    @Override
    public CaptchaData generateCharCaptcha() {
        try {
            // 生成验证码文本
            String code = charCaptchaProducer.createText();
            
            // 生成验证码图片
            BufferedImage image = charCaptchaProducer.createImage(code);
            
            // 转换为Base64
            String base64Image = convertImageToBase64(image);
            
            CaptchaData data = new CaptchaData();
            data.setCode(code);
            data.setImage(base64Image);
            
            log.debug("生成字符验证码成功: code={}", code);
            return data;
        } catch (Exception e) {
            log.error("生成字符验证码失败", e);
            throw new RuntimeException("生成验证码失败", e);
        }
    }

    @Override
    public CaptchaData generateMathCaptcha() {
        try {
            // 生成数学运算表达式
            String expression = mathCaptchaProducer.createText();
            
            // 生成验证码图片
            BufferedImage image = mathCaptchaProducer.createImage(expression);
            
            // 计算表达式结果作为验证码
            String code = calculateMathExpression(expression);
            
            // 转换为Base64
            String base64Image = convertImageToBase64(image);
            
            CaptchaData data = new CaptchaData();
            data.setCode(code);
            data.setImage(base64Image);
            
            log.debug("生成数学运算验证码成功: expression={}, code={}", expression, code);
            return data;
        } catch (Exception e) {
            log.error("生成数学运算验证码失败", e);
            throw new RuntimeException("生成验证码失败", e);
        }
    }

    /**
     * 将图片转换为Base64编码
     */
    private String convertImageToBase64(BufferedImage image) throws IOException {
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
            return Base64.getEncoder().encodeToString(os.toByteArray());
        } finally {
            os.close();
        }
    }

    /**
     * 计算数学表达式结果
     */
    private String calculateMathExpression(String expression) {
        try {
            // 移除等号
            String expr = expression.replace("=?", "").trim();
            
            // 简单的数学运算解析
            if (expr.contains("+")) {
                String[] parts = expr.split("\\+");
                int result = Integer.parseInt(parts[0].trim()) + Integer.parseInt(parts[1].trim());
                return String.valueOf(result);
            } else if (expr.contains("-")) {
                String[] parts = expr.split("-");
                int result = Integer.parseInt(parts[0].trim()) - Integer.parseInt(parts[1].trim());
                return String.valueOf(result);
            } else if (expr.contains("*") || expr.contains("×")) {
                String[] parts = expr.split("[*×]");
                int result = Integer.parseInt(parts[0].trim()) * Integer.parseInt(parts[1].trim());
                return String.valueOf(result);
            }
            
            return "0";
        } catch (Exception e) {
            log.error("计算数学表达式失败: expression={}", expression, e);
            return "0";
        }
    }
}
